package net.hn.hnms.biz.project.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.project.domain.PlanInvestment;
import net.hn.hnms.biz.project.domain.ProjectInfo;
import net.hn.hnms.biz.project.mapper.PlanInvestmentMapper;
import net.hn.hnms.biz.project.mapper.ProjectInfoMapper;
import net.hn.hnms.biz.project.request.PlanInvestmentReq;
import net.hn.hnms.biz.project.service.PlanInvestmentService;
import net.hn.hnms.biz.project.service.ProjectInfoService;
import net.hn.hnms.biz.project.vo.PlanInvestmentVo;
import net.hn.hnms.biz.project.vo.ProjectInfoVo;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class PlanInvestmentServiceImpl extends BaseService<PlanInvestment, PlanInvestmentVo> implements PlanInvestmentService {


    @Autowired
    private PlanInvestmentMapper planInvestmentMapper;


    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    @Autowired
    private ProjectInfoService projectInfoService;


    @Override
    public int insert(PlanInvestmentReq planWashing) {
        PlanInvestment insertObj = new PlanInvestment();
        copyProperties(planWashing, insertObj, planWashing.getInvestmentPlanType(), "planStartDate", "planEndDate");
        //自动生成 计划名称 计划编号
        insertObj.setInvestmentPlanName(generatePlanName(planWashing.getInvestmentPlanType(), insertObj.getPlanStartDate()));
        insertObj.setInvestmentPlanCode(generatePlanCode(planWashing.getInvestmentPlanType(), insertObj.getPlanStartDate()));
        insertObj.setStatus("0");
        QueryWrapper<PlanInvestment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("investment_plan_code", insertObj.getInvestmentPlanCode());
        if (planInvestmentMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planInvestmentMapper.insert(insertObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        planInvestmentMapper.deleteBatchIds(idList);
    }

    @Override
    public void updateById(PlanInvestmentReq planWashing) {
        if (StrUtil.isBlank(planWashing.getInvestmentPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanInvestment updateObj = new PlanInvestment();
        copyProperties(planWashing, updateObj, planWashing.getInvestmentPlanType(), "planStartDate", "planEndDate");
        updateObj.setInvestmentPlanName(generatePlanName(planWashing.getInvestmentPlanType(), updateObj.getPlanStartDate()));
        updateObj.setInvestmentPlanCode(generatePlanCode(planWashing.getInvestmentPlanType(), updateObj.getPlanStartDate()));
        QueryWrapper<PlanInvestment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("investment_plan_code", updateObj.getInvestmentPlanCode());
        queryWrapper.ne("investment_plan_id", updateObj.getInvestmentPlanId());
        if (planInvestmentMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planInvestmentMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    @Override
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanInvestment planMining = planInvestmentMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planInvestmentMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }

    @Override
    public ResponsePage<PlanInvestmentVo> selectPageList(PlanInvestmentReq planWashing, PageQuery pageQuery) {
        if (StrUtil.isNotBlank(planWashing.getProjectType())) {
            List<ProjectInfoVo> projectListByType = projectInfoService.getProjectListByType(planWashing.getProjectType());
            List<String> projectIds = projectListByType.stream()
                    .map(ProjectInfoVo::getProjectId)
                    .collect(Collectors.toList());
            planWashing.setProjectIds(projectIds);
        }
        Page<PlanInvestment> page = planInvestmentMapper.selectPage(pageQuery.build(), buildQuery(planWashing).orderByDesc(PlanInvestment::getInvestmentPlanCode).orderByDesc(PlanInvestment::getCreateTime));

        List<PlanInvestmentVo> list = page.getRecords().stream().map(o -> convert(o, PlanInvestmentVo.class, o.getInvestmentPlanType(),
                "planStartDate", "planEndDate")).collect(Collectors.toList()).stream().collect(Collectors.toList());
        for (PlanInvestmentVo watchVO : list) {
            if (StrUtil.isNotBlank(watchVO.getProjectId())) {
                ProjectInfo projectInfo = projectInfoMapper.selectById(watchVO.getProjectId());
                if (projectInfo != null) {
                    watchVO.setProjectType(projectInfo.getProjectType());
                    watchVO.setProjectDate(projectInfo.getProjectDate());
                    watchVO.setTotalAmount(projectInfo.getTotalAmount());
                    watchVO.setProjectName(projectInfo.getProjectName());
                }
            }
        }
        return new ResponsePage<>(list, page.getTotal());
    }

    @Override
    public List<PlanInvestmentVo> selectList(PlanInvestmentReq planWashing) {
        List<PlanInvestment> list = planInvestmentMapper.selectList(buildQuery(planWashing));
        return list.stream().map(o -> convert(o, PlanInvestmentVo.class, o.getInvestmentPlanType(), "planStartDate", "planEndDate")).collect(Collectors.toList());

    }


    private LambdaQueryWrapper<PlanInvestment> buildQuery(PlanInvestmentReq req) {
        LambdaQueryWrapper<PlanInvestment> lqw = new LambdaQueryWrapper<PlanInvestment>()
                .like(StrUtil.isNotBlank(req.getInvestmentPlanCode()), PlanInvestment::getInvestmentPlanCode, req.getInvestmentPlanCode())
                .like(StrUtil.isNotBlank(req.getInvestmentPlanName()), PlanInvestment::getInvestmentPlanName, req.getInvestmentPlanName())
                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanInvestment::getMineCode, req.getMineCode())
                .in(!CollectionUtils.isEmpty(req.getProjectIds()), PlanInvestment::getProjectId, req.getProjectIds())
                .eq(StrUtil.isNotBlank(req.getInvestmentPlanType()), PlanInvestment::getInvestmentPlanType, req.getInvestmentPlanType())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanInvestment::getStatus, req.getStatus());
//                .and(o->o.eq(req.getMineCode()!=null, PlanWashing::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanWashing::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }
}
